/*
 DNN Content Builder - sourceforge.net/projects/dnncb
 Copyright (c) 2004-2008
 by Emerson Lopes (emersonlopes@gmail.com)

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Text;
using DotNetNuke.Entities.Portals;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using System.Web.UI;

namespace DNNContentBuilder.UserControls
{
	/// <summary>
	/// Summary description for ScheduleContent.
	/// </summary>
	public class ScheduleContent : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.RadioButton PublishNow;
		protected System.Web.UI.WebControls.RadioButton PublishScheduled;
		protected System.Web.UI.WebControls.Label lblPublish;
		protected System.Web.UI.WebControls.Calendar Calendar;
		protected System.Web.UI.WebControls.Label lblTime;
		protected System.Web.UI.WebControls.TextBox txtTime;
		protected System.Web.UI.WebControls.LinkButton btPublish;
		protected System.Web.UI.WebControls.LinkButton btCancel;
		private   string parameters;
		private   System.Collections.Hashtable hash = new Hashtable();
	
		public const string resource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/ScheduleContent";
		private const string eventResource = "~/DesktopModules/DNNContentBuilder/App_LocalResources/MetaDataEvent";

		private void Page_Load(object sender, System.EventArgs e)
		{
			
			if (!Request.IsAuthenticated) {
				throw new Exception("Not authenticated");
			}
			
			try {
				string settings = Request.Params["settings"];
				parameters = ((StringBuilder)DataCache.GetCache(settings)).ToString();
			}
			catch (Exception ) {
					throw new Exception("Settings?");
			}
			
			foreach (string parameter in parameters.Split('&')) {
				hash.Add(parameter.Split('=')[0], parameter.Split('=')[1]);
			}
			
			string key = hash["ps"].ToString();
			
			lblTime.Text			= Commons.GetLocalizedString("label_Time", resource);
			lblPublish.Text 		= Commons.GetLocalizedString("label_Publish", resource);
			btCancel.Text    		= Commons.GetLocalizedString("button_Cancel", resource);
			btPublish.Text    		= Commons.GetLocalizedString("button_Publish", resource);
			PublishNow.Text 		= Commons.GetLocalizedString("radio_PublishNow", resource);
			PublishScheduled.Text 	= Commons.GetLocalizedString("radio_Schedule", resource);
			
		}

		private void btPublish_Click(object sender, System.EventArgs e)
		{
			PublishContent();

			CloseThis();
		}
		
		private void btCancel_Click(object sender, System.EventArgs e)
		{
			CloseThis();
		}
		
		private void CloseThis() {
			string key = String.Format("{0}Startup", this.GetType().FullName);
            ClientScriptManager cs = Page.ClientScript;
			string postback = hash["pb"].ToString();
			
			string script = String.Format(@"
				<script language=""javascript"">
					window.opener.{0}
					window.close();
				</script>", postback);

			if (!ClientScript.IsStartupScriptRegistered(key))
			{
                cs.RegisterStartupScript(Page.GetType(),key, script);
			}

			//Removing publishing settings session, so an illegal attempt to reload this page would throw an exception
			DataCache.RemoveCache(Request.Params["settings"]);
		}

		private void PublishContent()
		{
			string metadata = hash["metadataId"].ToString();
			
			int    userId   = int.Parse(hash["uid"].ToString());

			ArgumentValidator.CheckForNullReference(metadata, "metadata");
			ArgumentValidator.CheckForEmptyString(metadata, "metadata");
			
			string taskId = hash["tid"].ToString();
			
			if (taskId != "") {
				MetaDataTaskController mtController = new MetaDataTaskController();
			
				MetaDataTaskInfo mtInfo = mtController.GetItem(int.Parse(taskId));
			
				mtInfo.Status = TaskStatus.Finished;
				mtInfo.FinishDate = System.DateTime.Now;
			
				mtController.Update(mtInfo);
			}

			MetaDataController mdController = new MetaDataController();

			foreach (string metadataId in metadata.Split(';'))
			{
				MetaDataEventController meController = new MetaDataEventController();
				
				MetaDataInfo mdInfo = mdController.GetItem(Int32.Parse(metadataId));

				mdInfo.Status = MetaDataStatus.Published;

				MetaDataEventInfo meInfo = new MetaDataEventInfo();
					
				meInfo.Description = Commons.GetLocalizedString("label_ContentPublished", eventResource);
				meInfo.Details     = mdInfo.Title;
				meInfo.MetaDataId  = mdInfo.MetaDataId;
				meInfo.EventDate   = System.DateTime.Now;
				meInfo.UserId      = userId;
				meInfo.EventType   = TypeOfEvent.Published;
				
				if (!PublishNow.Checked)
				{
					DateTime schedule = Calendar.SelectedDate;

					if (txtTime.Text.Length > 0)
					{
						TimeSpan ts = TimeSpan.Parse(txtTime.Text);
						schedule = schedule.Add(ts);
					}

					mdInfo.Status = MetaDataStatus.Working;
					mdInfo.ScheduleDate = schedule;
					meInfo.EventType = TypeOfEvent.Scheduled;
					meInfo.Description = Commons.GetLocalizedString("label_ContentScheduled", eventResource);
				}

				meController.Add(meInfo); //Content log updated
				
				mdController.Update(mdInfo);
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btPublish.Click += new System.EventHandler(this.btPublish_Click);
			this.btCancel.Click += new System.EventHandler(this.btCancel_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}

